package com.sample.client.repo

import com.loyal.client.ClientConfig
import com.loyal.client.RetroCallManager
import com.loyal.client.error.ExceptHelper
import com.sample.client.data.ResponseData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.coroutines.cancellation.CancellationException

abstract class BaseRepoImpl<T> {

    protected var repoServer: T? = null
    abstract fun serverClass(): Class<T>

    init {
        updateConfig()
    }

    fun updateConfig() {
        val retroManager = RetroCallManager.getInstance()
        retroManager.build(ClientConfig.getInstance())
        repoServer = retroManager.createServer(serverClass())
    }

    open suspend fun <T : Any> loadRequest(
        what: Int = 2,
        block: suspend () -> T?
    ): ResponseData<T?> {
        return try {
            val data = withContext(Dispatchers.IO) {
                block.invoke()
            }
            ResponseData.success(what = what, data = data)
        } catch (e: Exception) {
            val error = if (e is CancellationException)
                "已取消操作"
            else ExceptHelper.get(e)
            ResponseData.fail(what = what, message = error)
        }
    }
}